package com.example.onlinemonitoring.comCenter;

import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.model.Arcsupcoilsensor;
import com.example.onlinemonitoring.model.Dljfsensor;
import com.example.onlinemonitoring.model.common.MyResult;
import com.example.onlinemonitoring.model.Arcsupcoilhistory;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.serviceImpl.ArcsupcoilsensorServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Scope;
import java.text.ParseException;
import java.util.Date;
import com.example.onlinemonitoring.Util.IEEE754Utils;
import javax.annotation.Resource;

/**
 * 消弧线圈控制器
 */
@Service("arcsupcoilCom")
@Scope("prototype")
public class ArcsupcoilCom extends CommPortManager {
    @Autowired
    private ArcsupcoilsensorServiceImpl arcsupcoilsensorServiceImpl;
    int YXCoilStatus = 0;
    int YXLine = 0;

    @Override
    public void receiveData(String str) {
        try {
            str = str.toUpperCase();
            setText(str);
            // 条件判断自己写
            //int addr = parseHex4(str.substring(0, 2));
            //reSend[addr] = 0;
            
            Integer startIndex = 12;// 数据起始位置
            if ((!"71".equals(str.substring(12, 14))))
                return;
            String cmdtip;
            if (str.length() >= 48) {
                cmdtip = str.substring(14, 16);
            } else {
                //cmdtip = str.substring(2, 4);
                return;
            }
            //addrindex = ad.getAddrmin();
             int num = 0;


            if (cmdtip.equals("61"))// 遥测
            {
               // String addrstr = str.substring(18, 20);
                //Integer addr = parseHex4(addrstr);

                int LastVref = 0;
                float LastCurrent = 0;
                float LastCapacity = 0;
                float LastCapCurrent = 0;
                float LastTdegree = 0;
                float LastResCurrent = 0;
                int LastGear = 0;
                //if(addrindex==0)
                {
                    Arcsupcoilsensor arcsupcoilsensor = new Arcsupcoilsensor();
                    // 设置设备地址
                    arcsupcoilsensor.setStationid(ad.getStationid());
                    arcsupcoilsensor.setDeviceaddr(addrindex);
                    MyResult<Arcsupcoilsensor> res = arcsupcoilsensorServiceImpl.getList(arcsupcoilsensor);
                    // 查询对象
                    num = res.getCount();
                    for (int i = 0; i < num; i++) {
                        Arcsupcoilsensor record = res.getData().get(i);
                        if (record == null) {
                            setText("当前数据库无监测点：设备地址" + addrindex + "的监测点" + (i+1) +" ！ 请先添加该监测点！");
                            return;
                        }
                        setText("设备返回数据： 站点号：" + ad.getStationid() + "设备地址" + addrindex +" 的监测点" + (i + 1));
                        LastVref = IEEE754Utils.strbytesToSingleTurn(str.substring(26 + 48 * i, 30 + 48 * i)).intValue();
                        // LastVref = HexUtil.byte2int(mybyte_Vref);
                        LastCurrent = IEEE754Utils.strbytesToSingleTurn(str.substring(30 + 48 * i, 34 + 48 * i)).floatValue() / 100;
                        LastCapacity = IEEE754Utils.strbytesToSingleTurn(str.substring(38 + 48 * i, 42 + 48 * i)).floatValue() / 100;
                        LastCapCurrent = IEEE754Utils.strbytesToSingleTurn(str.substring(42 + 48 * i, 46 + 48 * i)).floatValue() / 100;
                        //LastCapCurrent = parseHex4(str.substring(42 + 48 * i, 46 + 48 * i)) / 100;
                        
                        // int carr = parseHex4(str.substring(52 + 48 * i, 54 + 48 * i));
                        // //int aa=carr & 0x80;
                        // if ((carr & 0x80) >0) {
                        //     int LastTdegree1 = parseHex4(str.substring(50 + 48 * i, 54 + 48 * i));
                        //      LastTdegree1 = ~LastTdegree1;
                        //     LastTdegree1 = LastTdegree1 + 0x01;
                        //     LastTdegree = LastTdegree1 / 1000;
                        // } else {
                        //     LastTdegree = parseHex4(str.substring(50 + 48 * i, 54 + 48 * i)) / 1000;
                        // }
                        LastTdegree = IEEE754Utils.strbytesToSingleTurn(str.substring(50 + 48 * i, 54 + 48 * i)).floatValue() / 10;
                        //carr = parseHex4(str.substring(56 + 48 * i, 58 + 48 * i));

                        // if ((carr & 0x80) == 1) {
                        //     int LastResCurrent1 = parseHex4(str.substring(54 + 48 * i, 58 + 48 * i));
                        //     LastResCurrent1 = LastResCurrent1 - 0x01;
                        //     LastResCurrent1 = ~LastResCurrent1;
                        //     LastResCurrent = -LastResCurrent1 / 100;
                        // } else {
                        //     LastResCurrent = parseHex4(str.substring(54 + 48 * i, 58 + 48 * i)) / 100;
                        // }
                        LastResCurrent = IEEE754Utils.strbytesToSingleTurn(str.substring(54 + 48 * i, 58 + 48 * i)).floatValue() / 100;
                        // byte[] mybyte_Gear = HexUtil.hexString2Bytes(str.substring(62 + 48*i, 66 +
                        // 48*i));
                        LastGear = IEEE754Utils.strbytesToSingleTurn(str.substring(62 + 48 * i, 66 + 48 * i)).intValue() / 4;

                        setText("中点电压：" + LastVref + "V" + " 中点电流：" + LastCurrent + "A" + " 电容：" + LastCapacity + "uF");
                        setText("电容电流：" + LastCapCurrent + "A" + " 脱谐度：" + LastTdegree + "%" + " 残流：" + LastResCurrent
                                + "A");
                        setText("档位：" + LastGear + "档");

                        // String stlyestr = record.getStyle();
                        // if((stlyestr==null)||(stlyestr.equals("")))
                        // {
                        // stlyestr="awcurrent|1|A相泄漏电流,bwcurrent|1|B相泄漏电流,cwcurrent|1|C相泄漏电流,tandeltaa|1|A相介损,tandeltab|1|B相介损,tandeltac|1|C相介损";
                        // record.setStyle(stlyestr);
                        // }
                        record.setPointaddr(i+1);    
                        record.setLastvref(LastVref);
                        record.setLastcurrent(LastCurrent);
                        record.setLastcapacity(LastCapacity);
                        record.setLastcapcurrent(LastCapCurrent);
                        record.setLasttdegree(LastTdegree);
                        record.setLastrescurrent(LastResCurrent);
                        int StatusChange = isnull(record.getLaststatuschange());
                        int Gear = isnull(record.getLastgear());
                        if (LastGear != Gear)
                            StatusChange++;
                        record.setLastgear(LastGear);
                        record.setLaststatuschange(StatusChange);
                        AddAndUpdateyc(record);
                    }
                }

            }
            if (cmdtip.equals("F4"))// 遥信
            {
                //String addrstr = str.substring(18, 20);
                //Integer addr = parseHex4(addrstr);

                // char[] carr = parseHex4(str.substring(30, 32));
                int lt = parseHex4(str.substring(30, 32));
                int index = 0;
                byte Line[] = new byte[48];
                byte Linetmp[] = new byte[6];

                if (lt > 0)
                Linetmp[0] = (byte)lt;
                
                //lt = parseHex4(str.substring(30, 32));
                //if (lt > 0)
                 //   Line[1] = (byte)lt;
                
                lt = parseHex4(str.substring(32, 34));
                if (lt > 0)
                Linetmp[1] = (byte)lt;

                lt = parseHex4(str.substring(38, 40));
                if (lt > 0)
                Linetmp[2] = (byte)lt;

                lt = parseHex4(str.substring(40, 42));
                if (lt > 0)
                Linetmp[3] = (byte)lt;

                lt = parseHex4(str.substring(42, 44));
                if (lt > 0)
                Linetmp[4] = (byte)lt;

                lt = parseHex4(str.substring(44, 46));
                if (lt > 0)
                Linetmp[5] = (byte)lt;


                //if(addr==0)
                {
                    Arcsupcoilsensor arcsupcoilsensor = new Arcsupcoilsensor();
                    // 设置设备地址
                    arcsupcoilsensor.setStationid(ad.getStationid());
                    arcsupcoilsensor.setDeviceaddr(1);
                    MyResult<Arcsupcoilsensor> res = arcsupcoilsensorServiceImpl.getList(arcsupcoilsensor);
                    // 查询对象
                    num = res.getCount();
                    for (int i = 0; i < num; i++) {
                        
                    String strCoilStatus1 = "";
                    String strCoilStatus2 = "";

                    YXCoilStatus = parseHex4(str.substring(26 + 2 * i, 28 + 2 * i));

                    //strCoilStatus = record.getLastcoilstatus();

                    // if ((YXCoilStatus & 0x80) > 0) {
                    //     strCoilStatus = strCoilStatus + "接地 ";
                    // }  
                    // if ((YXCoilStatus & 0x40) > 0) {
                    //     strCoilStatus = strCoilStatus + "拒动 ";
                    // }  
                    // if ((YXCoilStatus & 0x20) > 0) {
                    //     strCoilStatus = strCoilStatus + "档位到头 ";
                    // }  
                    // if ((YXCoilStatus & 0x10) > 0) {
                    //     strCoilStatus = strCoilStatus + "档位到底 ";
                    // }  
                    if ((YXCoilStatus & 0x08) > 0) {
                        strCoilStatus1 = strCoilStatus1 + "并运 ";
                    } 
                    else{
                        strCoilStatus1 = strCoilStatus1 + "独运 ";
                    } 
                    if ((YXCoilStatus & 0x04) > 0) {
                        strCoilStatus2 = strCoilStatus2 + "手动 ";
                    }  
                    if ((YXCoilStatus & 0x04) == 0) {
                        strCoilStatus2 = strCoilStatus2 + "自动 ";
                    }  
                    // if ((YXCoilStatus & 0x02) > 0) {
                    //     strCoilStatus = strCoilStatus + "母线接地 ";
                    // }  
                    // if ((YXCoilStatus & 0x01) > 0) {
                    //     strCoilStatus = strCoilStatus + "故障 ";
                    // }
                    // if(i==0)
                    // for(int j=0;j<3;j++)
                    // {
                    //    if ((Linetmp[j] & 0x01) > 0)
                    //     Line[j * 8] = 1;
                    //    if ((Linetmp[i] & 0x02) > 0)
                    //    Line[j * 8 + 1] = 1;
                    //    if ((Linetmp[j] & 0x04) > 0)
                    //    Line[j * 8 + 2] = 1;
                    //    if ((Linetmp[j] & 0x08) > 0)
                    //    Line[j * 8 + 3] = 1;
                    //    if ((Linetmp[j] & 0x10) > 0)
                    //    Line[j * 8 + 4] = 1;
                    //    if ((Linetmp[j] & 0x20) > 0)
                    //    Line[j * 8 + 5] = 1;
                    //    if ((Linetmp[j] & 0x40) > 0)
                    //    Line[j * 8 + 6] = 1;
                    //    if ((Linetmp[j] & 0x80) > 0)
                    //    Line[j * 8 + 7] = 1;
                    // }
                    // if(i==1)
                    // for(int j=3;j<6;j++)
                    // {
                    //    if ((Linetmp[j] & 0x01) > 0)
                    //     Line[j * 8] = 1;
                    //    if ((Linetmp[j] & 0x02) > 0)
                    //    Line[j * 8 + 1] = 1;
                    //    if ((Linetmp[j] & 0x04) > 0)
                    //    Line[j * 8 + 2] = 1;
                    //    if ((Linetmp[j] & 0x08) > 0)
                    //    Line[j * 8 + 3] = 1;
                    //    if ((Linetmp[j] & 0x10) > 0)
                    //    Line[j * 8 + 4] = 1;
                    //    if ((Linetmp[j] & 0x20) > 0)
                    //    Line[j * 8 + 5] = 1;
                    //    if ((Linetmp[j] & 0x40) > 0)
                    //    Line[j * 8 + 6] = 1;
                    //    if ((Linetmp[j] & 0x80) > 0)
                    //    Line[j * 8 + 7] = 1;
                    // }
                        Arcsupcoilsensor record = res.getData().get(i);
                        if (record == null) {
                            setText("当前数据库无监测点：设备地址" + addrindex + "的监测点" + i+1 +" ！ 请先添加该监测点！");
                            return;
                        }
                    setText("设备返回数据： 站点号：" + ad.getStationid() + " 设备地址：" + addrindex+ "的监测点" + (i+1));
                    record.setLastcoilstatus(YXCoilStatus);
                    record.setLastcoilstatusmsg1(strCoilStatus1);
                    record.setLastcoilstatusmsg2(strCoilStatus2);
                    //record.setLastline(Line);
                    record.setPointaddr(i+1);    
                    AddAndUpdateyx(record);
                    }
                }
            }
            addrindex++;
        } catch (Exception ex) {
            ex.printStackTrace();
            setText("从设备返回的数据有误！请检查串口！");
        }
    }

    @Transactional
    private void AddAndUpdateyc(Arcsupcoilsensor record) {
        int alarmLevel = 0;// 报警等级
        String alarmMessage = "";// 报警消息
        // 报警逻辑
        // 这里写报警逻辑

        // record.setLastalarmlevel(alarmLevel);
        // record.setLastalarmmessage(alarmMessage);
        record.setLastcommunicationstatus(0);
        record.setLastdatatime(new Date());
        record.setLasthisdatatime(addHistory(record));
        if (arcsupcoilsensorServiceImpl.Update(record, false) == 0) {
            setText("更新实时数据失败，请检查数据库连接");
        }
    }

    @Transactional
    private void AddAndUpdateyx(Arcsupcoilsensor record) {
        int alarmLevel = 0;// 报警等级
        String alarmMessage = "";// 报警消息
        String jdMessage = "";// 接地消息
        String strLineName = record.getLinename();
        String LineName[] =strLineName.split(",");
        byte Line[] = record.getLastline();
        String strLine = "";
        int lt = 0;
        // 报警逻辑
        // 这里写报警逻辑

        //alarmMessage += strCoilStatus;
        if ((YXCoilStatus & 0x80) > 0) {
            alarmMessage = alarmMessage + "接地告警 ";
            alarmLevel = 2;
        }  
        if ((YXCoilStatus & 0x40) > 0) {
            alarmMessage = alarmMessage + "拒动 ";
            alarmLevel = 2;
        }  
        // if ((YXCoilStatus & 0x20) > 0) {
        //     //strCoilStatus = strCoilStatus + "档位到头 ";
        //     alarmLevel = 1;
        // }  
        // if ((YXCoilStatus & 0x10) > 0) {
        //     //strCoilStatus = strCoilStatus + "档位到底 ";
        //     alarmLevel = 1;
        // }  
        if ((YXCoilStatus & 0x08) > 0) {
            //strCoilStatus = strCoilStatus + "联机 ";
        }  
        if ((YXCoilStatus & 0x04) > 0) {
            //strCoilStatus = strCoilStatus + "手动 ";
        }  
        if ((YXCoilStatus & 0x04) == 0) {
            //strCoilStatus = strCoilStatus + "自动 ";
        }  
        if ((YXCoilStatus & 0x02) > 0) {
            alarmMessage = alarmMessage + "母线接地 ";
            alarmLevel = 2;
            strLine =  "母线接地 ";
        }  
        if ((YXCoilStatus & 0x01) > 0) {
            alarmMessage = alarmMessage + "故障 ";
            alarmLevel = 2;
        }

        // if(record.getPointaddr()==1)
        // for(int i=0;i<24;i++)
        // {
        //     if (Line[i] > 0)
        //     {
        //         if(LineName.length>=i+1)
        //             strLine = strLine + "接地线路：" + String.format("%02d", i+1) + " 名称：" + LineName[i] +"\r\n";     
        //         else
        //             strLine = strLine + "接地线路：" + String.format("%02d", i+1) +"\r\n";  
        //     }

        // }
        // if(record.getPointaddr()==2)
        // for(int i=24;i<48;i++)
        // {
        //     if (Line[i] > 0)
        //     {
        //         if(LineName.length>=i+1)
        //             strLine = strLine + "接地线路：" + String.format("%02d", i+1) + " 名称：" + LineName[i] +"\r\n";     
        //         else
        //             strLine = strLine + "接地线路：" + String.format("%02d", i+1) +"\r\n";  
        //     }

        // }
       // if (Line == 0)
        //    strLine = strLine + "接地线路：" + "无" + "\r\n";
       // else
        //{
  
       // }

        jdMessage += strLine;
        //if (CoilStatus > 0)
           // alarmLevel = 2;
        Boolean isalarm = alarmLevel>0?true:false;
        GetNormalAlarm("接地告警",record.getDevicegroup(),
        record.getDeviceaddr(), record.getPointaddr(),
        record.getPointname(),alarmMessage,isalarm);
        record.setLastalarmlevel(alarmLevel);
        record.setLastjdmessage(jdMessage);
        record.setLastalarmmessage(alarmMessage);
        record.setLastcommunicationstatus(0);
        record.setLastdatatime(new Date());
        // record.setLasthisdatatime(addHistory(arcsupcoilsensorServiceImpl.getModel(record)));
        if (arcsupcoilsensorServiceImpl.Update(record, false) == 0) {
            setText("更新实时数据失败，请检查数据库连接");
        }
    }

    private Date addHistory(Arcsupcoilsensor sensor) {
        if (sensor != null) {
            if (sensor.getLasthisdatatime() == null) {
                add(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                    nowtime = HexUtil.todate(new Date()).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp() * 1000;
                } else {
                    timersp = ad.getHistimersp() * 1000;
                }
                if (lasttime + timersp < nowtime) {
                    add(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }

    private void add(Arcsupcoilsensor sensor) {
        Arcsupcoilhistory his = new Arcsupcoilhistory();
        his.setDeviceaddr(sensor.getDeviceaddr());
        his.setDevicegroup(sensor.getDevicegroup());
        his.setAlarmlevel(sensor.getLastalarmlevel());
        his.setAlarmmessage(sensor.getLastalarmmessage());
        his.setDatatime(sensor.getLastdatatime());
        his.setPointname(sensor.getPointname());
        his.setStationid(sensor.getStationid());
        his.setCommunicationstatus(sensor.getLastcommunicationstatus());
        // 需要添加自己定义的属性
        his.setVref(sensor.getLastvref());
        his.setCurrent(sensor.getLastcurrent());
        his.setCapacity(sensor.getLastcapacity());
        his.setCapcurrent(sensor.getLastcapcurrent());
        his.setTdegree(sensor.getLasttdegree());
        his.setRescurrent(sensor.getLastrescurrent());
        his.setGear(sensor.getLastgear());
        his.setCoilstatus(sensor.getLastcoilstatus());
        his.setLine(sensor.getLastline());
        arcsupcoilsensorServiceImpl.Add(his);
    }

    @Async("threadPool")
    public void startSendThread(Appdevice Appdevice) throws Exception {

        issend.put(Thread.currentThread().getId(), true);
        String cstr = "";
        String cmdtype = "";
        String nametype = "";
        int num = 0;
        int timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
        while (issend.get(Thread.currentThread().getId()) != null) {
        if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
        addrindex = Appdevice.getAddrmin();
        // cstr = String.format(Appdevice.getCmd(), String.format("%02X", addrindex));
        // try {
        //     Send(cstr);
        // } catch (Exception EX) {
        // setText(EX.toString());
        // }
        Arcsupcoilsensor sensor = new Arcsupcoilsensor();
        sensor.setStationid(ad.getStationid());
        sensor.setDevicegroup(ad.getDevicegroup());
        sensor.setDeviceaddr(addrindex);
        MyResult<Arcsupcoilsensor> res = arcsupcoilsensorServiceImpl.getList(sensor);
        // 查询对象
        num = res.getCount();
        for (int i = 0; i < num; i++) {
            Arcsupcoilsensor record = res.getData().get(i);
            if (record == null) {
                setText("当前数据库无监测点：设备地址" + addrindex + "的监测点" + (i+1) +" ！ 请先添加该监测点！");
                return;
            }
           if (record.getInuse() == 0)
               continue;
        Long t2 = record.getLastdatatime().getTime();
        Date nowtime = new Date();
        Long t1 = nowtime.getTime();
        long timelag = t1 - t2;
        long hoursp = timelag / (60 * 60 * 1000);
        long secondsp = timelag / 1000;
        if (secondsp > 10) {
            arcsupcoilsensorServiceImpl.UpdateStatus(ad, addrindex, 1);
        }
    }
        //setText("向" + Appdevice.getName() + "设备发送指令" + cstr);
        // reSend[addrindex]++;
        // if (reSend[addrindex] > 3) {
        // arcsupcoilsensorServiceImpl.UpdateStatus(ad, addrindex,1);
        // reSend[addrindex] = 0;
        // addrindex++;
        // }
        Thread.sleep(timersp);
        }
    }

    // @Async("threadPool")
    // public void startReceiveThread(){
    // isrecv.put(Thread.currentThread().getId(), true);
    // while (isrecv.get(Thread.currentThread().getId()) != null) {
    // //这里根据实际协议替换,解析方法recvCrc16;recvSum();
    // recv();
    // try {
    // Thread.sleep(interval);
    // } catch (InterruptedException e) {
    // e.printStackTrace();
    // }
    // }
    // }
}
